package com.jtjrenren.android.taxi.driver.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Environment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.jtjrenren.android.taxi.driver.R;
import com.library.weiget.UpAppDlg;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.library.utils.StringUtils;
import com.library.utils.AppUtils;

import java.io.File;

/**
 * Created by Administrator on 2015/12/29.
 *
 * @author wdl
 */
public class UIHelper {

    /**
     * 初始化相同的recyclearView
     *
     * @param context
     * @param view
     */
    public static void initVritalReclyView(Context context, RecyclerView view) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        view.setLayoutManager(layoutManager);
        view.setHasFixedSize(true);
    }

    public static void initHorReclyView(Context context, RecyclerView view) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        view.setLayoutManager(layoutManager);
        view.setHasFixedSize(true);
    }

    /**
     * 初始化相同的recyclearView
     *
     * @param context
     * @param view
     */
    public static void initGridReclyView(Context context, int spancount, RecyclerView view) {
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context, spancount, LinearLayoutManager.VERTICAL, true);
        view.setLayoutManager(layoutManager);
        view.setHasFixedSize(true);
    }


    /**
     * 初始化swiperefresh
     *
     * @param swipeLayout
     */
    public static void initSwipeRefreshLayout(SwipeRefreshLayout swipeLayout) {
        swipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
    }


    public static DisplayImageOptions getDisplayOptions() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                // // 设置图片在下载期间显示的图片
                .showImageOnLoading(R.mipmap.def_driver_icon)
                // // 设置图片Uri为空或是错误的时候显示的图片
                .showImageForEmptyUri(R.mipmap.def_driver_icon)
                // // 设置图片加载/解码过程中错误时候显示的图片
                .showImageOnFail(R.mipmap.def_driver_icon)
                .cacheInMemory(true)
                // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)
                // 设置下载的图片是否缓存在SD卡中
                .considerExifParams(true)
//                .imageScaleType(ImageScaleType.IN_SAMPLE_INT)// 设置图片以如何的编码方式显示
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//
                // 设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565)// 设置图片的解码类型
                // .decodingOptions(android.graphics.BitmapFactory.Options
                // decodingOptions)//设置图片的解码配置
                .considerExifParams(true)
                // 设置图片下载前的延迟
                // .delayBeforeLoading(int delayInMillis)//int
                // delayInMillis为你设置的延迟时间
                // 设置图片加入缓存前，对bitmap进行设置
                // 。preProcessor(BitmapProcessor preProcessor)
                .resetViewBeforeLoading(true)// 设置图片在下载前是否重置，复位
                // .displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角，弧度为多少
                .displayer(new FadeInBitmapDisplayer(100))// 淡入
                .build();
        return options;
    }


    /**
     * 初始化ImageLoader
     */
    public static void initImageLoader(Context context) {
        String filePath = Environment.getExternalStorageDirectory() +
                "/Android/data/" + context.getPackageName() + "/cache/";

        File cacheDir = StorageUtils.getOwnCacheDirectory(context, filePath);// 获取到缓存的目录地址
        // 创建配置ImageLoader(所有的选项都是可选的,只使用那些你真的想定制)，这个可以设定在APPLACATION里面，设置为全局的配置参数
        ImageLoaderConfiguration config = new ImageLoaderConfiguration
                .Builder(context)
                // .memoryCacheExtraOptions(480, 800) // max width, max
                // height，即保存的每个缓存文件的最大长宽
                // .discCacheExtraOptions(480, 800, CompressFormat.JPEG,
                // 75, null) // Can slow ImageLoader, use it carefully
                // (Better don't use it)设置缓存的详细信息，最好不要设置这个
                .threadPoolSize(3)// 线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new WeakMemoryCache())
                // .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024
                // * 1024)) // You can pass your own memory cache
                // implementation你可以通过自己的内存缓存实现
                .memoryCacheSize(2 * 1024 * 1024)
                // /.discCacheSize(50 * 1024 * 1024)
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())// 将保存的时候的URI名称用MD5
                // 加密
                // .discCacheFileNameGenerator(new
                // HashCodeFileNameGenerator())//将保存的时候的URI名称用HASHCODE加密
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                // .discCacheFileCount(100) //缓存的File数量
                .diskCache(new UnlimitedDiskCache(cacheDir))// 自定义缓存路径
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                .imageDownloader(new BaseImageDownloader(context, 5 *
                        1000, 30 * 1000)) // connectTimeout (5 s),
                // readTimeout(30)// 超时时间
                .writeDebugLogs() // Remove for release app
                .build();
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config);// 全局初始化此配置
    }

    public static void showCallPhoneDialog(final Activity context, final String phone) {
        showDialog(context, null, null, "呼叫" + phone + " ?", null, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppUtils.callPhone(context, phone);
            }
        });
    }

    public static void showDialog(Activity activity, final String okDesc, String cancleDesc, String content,
                                  final View.OnClickListener cancleListener, final View.OnClickListener okListener) {
        showDialogDownTime(activity, okDesc, cancleDesc, content, false, cancleListener, okListener);
    }

    public static CountDownTimer downTimer = null;

    public static void showDialogDownTime(Activity activity, final String okDesc, String cancleDesc, String content, boolean autoClose,
                                          final View.OnClickListener cancleListener, final View.OnClickListener okListener) {
        final AlertDialog dialog;
        if (Build.VERSION.SDK_INT >= 14) {
            dialog = new AlertDialog.Builder(activity,
                    AlertDialog.THEME_DEVICE_DEFAULT_DARK).create();
        } else {
            dialog = new AlertDialog.Builder(activity).create();
        }
        downTimer = null;
        if (autoClose) {
            downTimer = new CountDownTimer(10000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    if (dialog != null)
                        dialog.dismiss();
                }
            };

            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (downTimer != null)
                        downTimer.cancel();
                }
            });
        }


        LayoutInflater inflater = activity.getLayoutInflater();
        View layout = inflater.inflate(R.layout.dlg_alert, null);
        TextView tv_content = (TextView) layout.findViewById(R.id.dlg_alert_content);
        Button bt_cancle = (Button) layout.findViewById(R.id.dlg_alert_cancle);
        Button bt_ok = (Button) layout.findViewById(R.id.dlg_alert_ok);

        bt_cancle.setText(StringUtils.isEmpty(cancleDesc) ? "取消" : cancleDesc);
        bt_ok.setText(StringUtils.isEmpty(okDesc) ? "确认" : okDesc);
        tv_content.setText(StringUtils.isEmpty(content) ? "" : content);

        bt_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (cancleListener != null)
                    cancleListener.onClick(v);
            }
        });
        bt_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (okListener != null)
                    okListener.onClick(v);
            }
        });

        dialog.setView(layout);
        dialog.show();
        if (downTimer != null)
            downTimer.start();
    }

    public static UpAppDlg getUpVersionDlg(Context context) {
        UpAppDlg dlg = new UpAppDlg(context, R.style.dlg_common);
        return dlg;
    }

    public static ProgressDialog getProDialog(Context context, String title, String desc, boolean isoutCancle) {
        ProgressDialog proDialog = new ProgressDialog(context, ProgressDialog.THEME_HOLO_DARK);
        proDialog.setCanceledOnTouchOutside(isoutCancle);
        if (!StringUtils.isEmpty(title))
            proDialog.setTitle(title);
        if (!StringUtils.isEmpty(desc))
            proDialog.setMessage(desc);
        return proDialog;
    }
}
